package com.struts.utis;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;











import com.struts.pojo.User;
import com.struts.pojo.XmlVo;



public class XmlServiceLoadUtis {
	
	public static Map<String, Method> methodMap = new HashMap<String, Method>();//存放所有的方法
	public static Map<String,Integer> metParamLength = new HashMap<String,Integer>();//方法参数长度
	public static Map<String, String> beansMap = new HashMap<String, String>();//存放所有的service
	
	public static void getBeanAttr(String spath) throws Exception{
		System.out.println("XmlServiceLoadUtis:getBeanAttr开始加载");
		methodMap.clear();
		metParamLength.clear();
		
	
		
		SAXBuilder builder = new SAXBuilder();
		Document document = builder.build(new File(spath));
		Element root = document.getRootElement();
		
		Element actionform = root.getChild("beans");
		List<Element> form = actionform.getChildren();
		
		for(Element e:form) {
			String path = e.getAttributeValue("class");
			String name = e.getAttributeValue("name");
			Class clazz = Class.forName(path);
			Method[] methods= clazz.getMethods();
			
			beansMap.put(name, path);
			for (int j = 0; j < methods.length-9; j++) {//默认写了equest等方法
				methodMap.put(name+"."+methods[j].getName(), methods[j]);//key：service名字.方法史，value:当前方法				
				Class[] param = methods[j].getParameterTypes();
				metParamLength.put(name+"."+methods[j], Integer.valueOf(param.length));
			}
			
	
		}	
		System.out.println("XmlServiceLoadUtis:getBeanAttr开始成功");
	}
	
	public static void main(String args[]) {
		try {
			XmlServiceLoadUtis.getBeanAttr("D:\\workspace\\struts\\WebApp\\WEB-INF\\struts-service.xml");
			Map<String, Method> methodMapc=XmlServiceLoadUtis.methodMap;
	        
	    	Class clazz = Class.forName(beansMap.get("userService"));
			Object obj = clazz.newInstance();
			Method[] methods= clazz.getMethods();
	        Method met =methodMapc.get("userService.getUserList");
	        Object methodResult =met.invoke(obj,10);
	        System.out.println(methodResult.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
